/*
  This file is part of an addition to the model that reads, writes, and displays information
  This particular file reads, writes, and displays weather information.
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "ssm.h"

//kind of self-expainitory. prints the current weather information.
//An accurate description of what all the varables are can be found in ssm.h
void printWeather(Weather source)
{
	printf("rho		= %f\n", source.rho);
	printf("sun_rise	= %f\n", source.sun_rise);
	printf("sun_set		= %f\n", source.sun_set);
	printf("sun_length	= %f\n", source.sun_length);
	printf("phi_n		= %f\n", source.phi_n);
	printf("phi		= %f\n", source.phi);
	printf("theta		= %f\n", source.theta);
}

//This function writes the weather information to a file, most of the time, this file is called weather.str
//returns 0 on a sucsessful write
int writeWeather(char* filename, Weather *source)
{
	FILE *fp;
	if((fp=fopen(filename, "wb")) == NULL) 
	{//error opening file
  		fprintf(stderr,"ERROR: can not open %s for output\n", filename);
  		exit(1);
	}
	if((fwrite(source, sizeof(Weather), 1, fp)) == -1)
	{//write failed
		fprintf(stderr,"ERROR: could not write record\n");
	}
	fclose(fp);
	return 0;
}

//This function reads in weather information and stores it to dest
//returns 0 on a sucsessful read 
int readWeather(char* filename, Weather *dest)
{
	FILE *fp;
	if((fp=fopen(filename,"rb")) == NULL) 
	{//error opening file
  		fprintf(stderr,"ERROR: can not open %s for input\n", filename);
  		exit(1);
	}
	if((fread(dest, sizeof(Weather), 1, fp)) == -1)
	{//read failed
		fprintf(stderr,"ERROR: could not write record\n");
	}
	fclose(fp);
	return 0;
}
